package myaction.admin.studentinfo;

import myutil.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

public class StudentAddAction extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String s_id = request.getParameter("s_id");
        String s_name = request.getParameter("s_name");
        String s_username = request.getParameter("s_username");
        String s_password = request.getParameter("s_password");
        try {
            Connection cn = DbUtil.getConn();
            String sql1 = "select s_id from t_students where s_id = " + s_id + ";";
            Statement stmt = cn.createStatement();
            ResultSet rs = stmt.executeQuery(sql1);
            if (rs.next()) {
                request.setAttribute("CourseRepeat", "<script>alert('编号为" + s_id + "的学生已存在！')</script>");
                request.getRequestDispatcher("admin/studentadd.jsp").forward(request, response);
                rs.close();
                stmt.close();

            } else {
                    String sql = "insert into t_students(s_id,s_name,s_username,s_password) values(?,?,?,?)";
                    PreparedStatement ps = cn.prepareStatement(sql);
                    ps.setString(1, s_id);
                    ps.setString(2, s_name);
                    ps.setString(3, s_username);
                    ps.setString(4, s_password);
                    ps.executeUpdate();
                    ps.close();
                    response.sendRedirect("StudentFindAll");
            }
            cn.close() ;
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}


